<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Chengduleige extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        $sign = "";
        ksort($array);
        foreach ($array as $key => $value) {
            if (!$value && ($value != 0)) {
                continue;
            }
            $sign .= $key . "=" . $value . "&";
        }
        $sign .= "AppSecret=" . $secret_key;

        return strtolower(md5($sign));
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $account = (string)$bean->getAccount();
        $array = [
            'AppId' => strval($bean->getSupplierNum()),
            'SkuType' => 1,
            'Timestamp' => (float)millisecondTimestamp(),
            'SkuId' => (string)$bean->getGoodsId(),
            'OutTradeNo' => (string)$bean->getOrderNo(),//订单号
            'Number' => (int)($bean->getRechargeNum() * $bean->getStartCharging()),//充值数量,
            'Account'   => (string)$account,
            'AccountType' => 0,
            'SalesUnitPrice' => floatval($bean->getUnitPrice()),
            'NotifyUrl' => $bean->getNotifyUrl(), //异步回调地址
        ];
        $array['Sign'] = $this->sign($array, $bean->getSecretKey());

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('Status', '');
        $order_sn = $request->input('OutTradeNo', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['2', '3']))->setRechargeSuccess($status == '2');
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('success');
    }
}
